package com.grant.code.controller;

import com.grant.code.Main;
import com.grant.code.pojo.User;
import com.grant.code.service.UserService;
import com.grant.code.utils.DialogUtils;
import de.felixroske.jfxsupport.FXMLController;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.stage.Stage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;

import java.net.URL;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ResourceBundle;

@FXMLController
@Slf4j
public class EditUserController implements Initializable {

    private UserService userService;

    @FXML
    private TextField usernameField;
    @FXML private PasswordField passwordField;
    @FXML private DatePicker hiredatePicker;
    @FXML private ComboBox<String> roleCombo;
    @FXML private ComboBox<String> statusCombo;
    @FXML private Button saveBtn;
    @FXML private Button cancelBtn;

    private User originalUser;
    private final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");



    @Override
    public void initialize(URL location, ResourceBundle resources) {
        ApplicationContext context = Main.getContext();
        userService = context.getBean(UserService.class);
        System.out.println(context);

        // 初始化下拉框选项
        roleCombo.getItems().addAll("student", "manager","teacher");
        statusCombo.getItems().addAll("正常", "禁用");
    }


    public void initData(User user) {
        this.originalUser = user;
        usernameField.setText(user.getUserName());
        passwordField.setText(user.getUserPassword());
        
        // 日期格式转换
        if(user.getUserHiredate() != null) {
            hiredatePicker.setValue(LocalDate.parse(user.getUserHiredate(), dateFormatter));
        }
        
        roleCombo.getSelectionModel().select(user.getUserRole());
        statusCombo.getSelectionModel().select("0".equals(user.getUserStatus()) ? "正常" : "禁用");
    }

    public User getUpdatedUser() {
        originalUser.setUserName(usernameField.getText());
        originalUser.setUserPassword(passwordField.getText());
        
        if(hiredatePicker.getValue() != null) {
            originalUser.setUserHiredate(dateFormatter.format(hiredatePicker.getValue()));
        }
        
        originalUser.setUserRole(roleCombo.getValue());
        originalUser.setUserStatus("正常".equals(statusCombo.getValue()) ? "0" : "1");
        return originalUser;
    }

    // 添加事件处理方法
    @FXML
    private void handleSave() {
        log.info("保存用户信息");
        try {
            // 获取更新后的用户数据
            User updatedUser = getUpdatedUser();
            // 调用服务层保存数据（确保userService已注入）
            userService.updateUser(updatedUser);
            // 从数据库重新获取最新用户数据
            User freshUser = userService.getUserById(updatedUser.getUserId());
            // 关闭窗口前将新用户数据传递回主控制器
            ((MainController)Main.getPrimaryStage().getUserData()).updateCurrentUser(freshUser);
            // 关闭对话框
            closeWindow();
        } catch (Exception e) {
            e.printStackTrace();
            // 显示错误提示（需实现DialogUtils）
            DialogUtils.showErrorDialog("保存失败", "保存用户信息时发生错误：" + e.getMessage());
        }
    }

    @FXML
    private void handleCancel() {
        log.info("取消保存用户信息");
        closeWindow();
    }

    private void closeWindow() {
        // 获取当前Stage并关闭
        Stage stage = (Stage) saveBtn.getScene().getWindow();
        stage.close();
    }


}